use strict;
use warnings;
use Data::Dumper;
use Test::More 'no_plan';

use testsupport  ;

use_ok('Log');
use_ok('DBAccess');



my $log = Log->instance();

$log->setlevels('DEBUG',3);

my $d = DBAccess->instance();

is($d->opened,0,"isOpen");

eval {
    $d->filename("basic_test.db");
    is($d->opened,0,"correctly closed");
    $d->open();
    is($d->opened,1,"correctly opened");
    $d->close();
    is($d->opened,0,"correctly closed");
};
ok($@ eq '',"exception ".Dumper($@));
ok(-f "basic_test.db","file exists");

eval { 
    is($d->opened,0,"isOpen"); 
    $d->open();
    is($d->opened,1,"isOpen"); 
    $d->close();
    is($d->opened,0,"isOpen"); 
    $d->remove(); 
    is($d->opened,0,"isOpen"); 
}; 
ok($@ eq '',"exception ".Dumper($@)); ok(! -f "basic_test.db","file do not
    exists"); 

eval { 
    $d->do("create table CONFIG (var TEXT PRIMARY KEY, value TEXT)"); 
};
check_uuid(__FILE__,__LINE__,"2e6bfbc6-9e8a-36c4-9520-1b453d268ac4",$@);

$d->open();
eval {
    $d->do("create table CONFIG  (var TEXT PRIMARY KEY, value TEXT)");
    $d->do("create table CONFIG2 (var2 TEXT PRIMARY KEY, value2 TEXT, extra2 TEXT)");
};
ok($@ eq '',"exception create config/2".Dumper($@));
eval {
    $d->do("create___ table CONFIG (var TEXT PRIMARY KEY, value TEXT)");
};
check_uuid(__FILE__,__LINE__,"1b1bcd4a-6add-33ee-a090-4df809844b3e" ,$@);

eval {
    ok($d->do("insert into CONFIG (var,value) values ('ciccio1','pluto')"),"insert ciccio");
    ok($d->do("insert into CONFIG (var,value) values ('ciccio2','paperino')"),"insert ciccio2");
};
ok($@ eq '',"exception insert ".Dumper($@));

my $res = $d->exec_query("select var,value from CONFIG order by var asc",'var','value');
is(@$res,2,"num of inserts");
is($res->[0]->{'var'}, 'ciccio1',"ciccio1");
is($res->[1]->{'value'}, 'paperino',"paperino");


eval {
    ok($d->do("BEGIN TRANSACTION"),"BEGIN TRANSACTION");
    ok($d->do("INSERT OR REPLACE INTO CONFIG2 values ('Fabrizio','IS','greedy')"),"T/insert 1");
    ok($d->do("INSERT OR REPLACE INTO CONFIG2 values ('Daniele1','IS','tall')"),"T/insert 2");
    ok($d->do("INSERT OR REPLACE INTO CONFIG2 values ('Daniele2','INCREMENT','3')"),"T/insert 3");
    ok($d->do("COMMIT;"),"COMMIT");
};
ok($@ eq '',"exception statemente ".Dumper($@));

$res = $d->exec_query("select var2,value2,extra2 from CONFIG2 order by var2 asc",
			 'var2','value2','extra2');
is(@$res,3,"num of inserts STM");
is($res->[0]->{'var2'}, 'Daniele1',"Daniele1");
is($res->[1]->{'value2'}, 'INCREMENT',"INCREMENT");
is($res->[2]->{'extra2'}, 'greedy',"greedy");


my $log = Log->instance;
my $trace = $log->get_printable_stack();
print STDERR $trace;
$trace = $log->get_printable_filtered_stack();
print STDERR $trace;


